package com.raven.craft.code.generator.common.file.template;

import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.context.JavaBeanValueResolver;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import com.google.common.base.CaseFormat;
import lombok.SneakyThrows;

/**
 * @author raven
 * @date 2019-06-11 10:13
 */
public class HbsTemplateBuilder {

    private final Context context;
    private final Template template;

    @SneakyThrows
    public HbsTemplateBuilder(String templatePath, Object entity) {
        this.context = Context.newBuilder(entity)
                .resolver(JavaBeanValueResolver.INSTANCE)
                .build();

        TemplateLoader loader = new ClassPathTemplateLoader();
        Handlebars handlebars = new Handlebars(loader);

        handlebars.registerHelper("lowerUnderScore2LowerCamel",
                (Helper<String>) (str, options) -> CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, str));
        handlebars.registerHelper("upperCamel2LowerCamel",
                (Helper<String>) (str, options) -> CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, str));
        handlebars.registerHelper("lowerUnderScore2UpperCamel",
                (Helper<String>) (str, options) -> CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str));

        handlebars.registerHelper("plus", (Helper<Integer>) (a, options) -> {
            Integer b = options.param(0, 1);
            return a + b;
        });

        this.template = handlebars.compile(templatePath);

    }

    @SneakyThrows
    public String apply() {
        return template.apply(context);
    }
}
